package com.my.study.io;

import lombok.extern.slf4j.Slf4j;

import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Objects;
import java.util.function.Supplier;

/**
 * @author Carlos
 * @version 1.0
 * @Description TODO
 * @date 2021/6/26 11:53
 **/
@Slf4j
public class SteamCloseUtils {

    private SteamCloseUtils() {}

    public static void closeInputStream(InputStream in) {
        if (Objects.nonNull(in)) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void closeOutputStream(OutputStream out) {
        if (Objects.nonNull(out)) {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 通用流的关闭
     *
     * @param stream 流
     * @param errMsg 错误信息
     */
    public static void close(Closeable stream, Supplier<String> errMsg) {
        if (Objects.nonNull(stream)) {
            try {
                stream.close();
            } catch (IOException e) {
                log.error(errMsg.get(), e);
            }
        }
    }

}
